<?php
$orderbh = $_GET['orderbh'];
$operation = $_GET['operation'];
$config = (new Model('module_config'))->find(['admin'=>1]);
$params = [
	'key' => $config->key,
	'secret' => $config->secret,
	'orderbh' => $orderbh,
];
$detail = getModuleDetailApi($params);
\Log::error(json_encode($detail,320));
if($detail['status'] != 'success'){
	echo 'error';
	exit;
}
$pulgin = $detail['data'];
$module = (new Model('module_list'))->find(['plugin_id'=>$pulgin['id']]);
if(!$module->id){
	$module->plugin_id = $pulgin['id'];
	$module->title = $pulgin['title'];
	$module->orderbh = $pulgin['orderbh'];
	$module->desc = $pulgin['desc'];
	$module->plugin_type = $pulgin['type'];
	$module->logo = $pulgin['logo']??'';
	$module->ctime = time();
	$module->type = 2;
	$operation = 'install';
}
if($operation == 'upgrade' && $module->version == $pulgin['version']){
	echo 'error';
	exit;
}
$module->new_version = $pulgin['version'];
$module->expire_date = $pulgin['expire_date'];
$module->utime = time();


$addons_path = APP_PATH . '/Addons';
$params = [
	'key' => $config->key,
	'secret' => $config->secret,
	'orderbh' => $orderbh,
];
$downPlugin = downModuleApi($params);
\Log::error(json_encode($downPlugin,320));
if($downPlugin['status'] != 'success'){
	echo 'error';
	exit;
}
$file_name = $module->file_name;
if(!$file_name){
	$file_name = $downPlugin['data']['filename'];
	$module->file_name = $downPlugin['data']['filename'];
}
$resource = $downPlugin['data']['resource'];
$field = 'module';
$path = pub_path('module');
is_dir($path) or mkdir($path, 0777, true);
$file_path = $path.'/'.$file_name;
$res = file_put_contents($file_path, base64_decode($resource));

$zipName = $file_name;
$pathc = pub_path('module');
$pathcz = $pathc.'/'.$zipName;
if(!file_exists($pathcz)) exit;
$zipFile = new \Lib\PclZip($pathcz);
$zipPath = $addons_path;
// foreach ($zipFile->listContent() as $item) {

//        if (strpos($item['filename'], $plugin_dir . '/') === 0) {
//            $zipPath = $addons_path;

//            break;
//        }
//    }
$fileList = $zipFile->listContent();
$modulePathArr = explode('/', $fileList[0]['filename']);
$modulePath = $modulePathArr[0];

try {
    $re = $zipFile->extract(PCLZIP_OPT_PATH, $zipPath, PCLZIP_OPT_REPLACE_NEWER);
    if (!$re) \Log::error('解压失败:' . $zipFile->error_string);

} catch (\Exception $e) {
    \Log::error('插件解压失败，错误信息：' . $e->getMessage());
    exit;
}
//插件目录
$module->module_path  = $modulePath;

$xml = simplexml_load_file($addons_path.'/'.$modulePath.'/manifest.xml','SimpleXMLElement', LIBXML_NOCDATA);
$xml_arr = json_decode(json_encode($xml), 1);
$sqla = '';
if($operation == 'install'){
	// $module->version = $xml_arr['application']['version'];
	$module->identifie = $xml_arr['application']['identifie'];
	$module->name = $xml_arr['application']['name'];
	$module->title = $xml_arr['application']['title'];
	if(is_dir(ADDONS_PATH.DS.$modulePath.DS.'upgrade')){
		$versionDirs = getFileList(ADDONS_PATH.DS.$modulePath.DS.'upgrade');
		sort($versionDirs);
		if($versionDirs){
			foreach ($versionDirs as $versionDir) {
				$sqla = '';
				if(file_exists(ADDONS_PATH.DS.$modulePath.DS.'upgrade'.DS.$versionDir.DS.'Up.php')){
					$sqlArr = include(ADDONS_PATH.DS.$modulePath.DS.'upgrade'.DS.$versionDir.DS.'Up.php');
					foreach ((array)$sqlArr as $val) {
						$sqla .= $val;
					}
				}
				if($sqla){
					$resRunSql = updateRunSql($sqla);
					if($resRunSql['status'] !== 'success'){
						 \Log::error('sql执行错误:' . $resRunSql['msg']);
					}
				}
				$module->version = $versionDir;
			}
		}
	}
}else if($operation == 'upgrade'){
	if(is_dir(ADDONS_PATH.DS.$modulePath.DS.'upgrade')){
		$versionDirs = getFileList(ADDONS_PATH.DS.$modulePath.DS.'upgrade');
		sort($versionDirs);
		if($versionDirs){
			// arsort($versionDirs);
			$versionDirKey = array_keys($versionDirs,$module->version)[0];
			for ($i=$versionDirKey + 1; $i < count($versionDirs); $i++) { 
				$sqla = '';
				if(file_exists(ADDONS_PATH.DS.$modulePath.DS.'upgrade'.DS.$versionDirs[$i].DS.'Up.php')){
					$sqlArr = include(ADDONS_PATH.DS.$modulePath.DS.'upgrade'.DS.$versionDirs[$i].DS.'Up.php');
					foreach ((array)$sqlArr as $k => $val) {
						$sqla .= $val;
					}
				}
				if($sqla){
					$resRunSql = updateRunSql($sqla);
					if($resRunSql['status'] !== 'success'){
						 \Log::error('sql执行错误:' . $resRunSql['msg']);
					}
				}
				$module->version = $versionDirs[$i];
				$module->save();
			}
		}
	}
}


//添加菜单
// $menu = [];
// if($xml_arr['bindings']['menu'] != ''){
// 	$menuones = [];
// 	if(isset($xml_arr['bindings']['menu']['menuone']['menuonename'])){
// 		$menuones = [$xml_arr['bindings']['menu']['menuone']];
// 	}else{
// 		$menuones = $xml_arr['bindings']['menu']['menuone'];
// 	}
// 	foreach ($menuones as  $menuone) {
// 		$menu[$menuone['menuonename']] = [];
// 		$menu[$menuone['menuonename']]['name'] = $menuone['menuonename'];
// 		$menu[$menuone['menuonename']]['style'] = '<i class="'.$menuone['style'].'"></i>';
// 		$menutwos = [];
// 		if(isset($menuone['sub']['menunametwo'])){
// 			$menutwos = [$menuone['sub']];
// 		}else{
// 			$menutwos = $menuone['sub'];
// 		}
// 		foreach ($menutwos as $sub) {
// 			$link = 'Addons'.$sub['link'];
// 			$menu[$menuone['menuonename']]['sub'][] = ['name'=>$sub['menunametwo'],'file'=>$link];
// 		}
// 	}
// }
// $menu_str = '';
// $menu_str = '<?php $menu ='. var_export($menu,true) . ';return ["menu"=>$menu];';
// file_put_contents($addons_path.'/'.$modulePath.'/menu.php',$menu_str);

$module->status =  1;
$module->can_update = 0;
$module->save();
unlink($pathcz);
echo 'success';
exit;
